package com.kcsoft.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kcsoft.mapper.MessageMapper;
import com.kcsoft.pojo.Message;
import com.kcsoft.pojo.PageBean;
import com.kcsoft.pojo.Sessions;
import com.kcsoft.service.MessageService;
import com.kcsoft.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    MessageMapper messageMapper;


    @Override
    public List<Sessions> findByUser(String assistantId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        return messageMapper.findByUser(id, assistantId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMsg(List<Message> messages) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        for (Message message : messages) {
            String question = message.getQuestion();
            String sessionId = message.getSessionId();
            String answer = message.getAnswer();
            LocalDateTime createTime = message.getCreateTime();
            Message msg = messageMapper.hasMessage(question, sessionId, answer, createTime, id);
            if (msg != null) {
                continue;
            }
            messageMapper.saveMsg(question, sessionId, answer, createTime, id);
        }
    }

    @Override
    public PageBean<Message> list(Integer pageNum, Integer pageSize, String sessionId) {
        PageBean<Message> pb = new PageBean<>();

        PageHelper.startPage(pageNum, pageSize);

        List<Message> al = messageMapper.list(sessionId);

        Page<Message> m = (Page<Message>) al;

        pb.setTotal(m.getTotal());

        pb.setItems(m.getResult());

        return pb;
    }

    @Override
    public PageBean<Message> listAll(Integer pageNum, Integer pageSize, Integer id) {
        PageBean<Message> pb = new PageBean<>();

        PageHelper.startPage(pageNum, pageSize);

        List<Message> al = messageMapper.listAll(id);

        Page<Message> m = (Page<Message>) al;

        pb.setTotal(m.getTotal());

        pb.setItems(m.getResult());

        return pb;

    }
}
